import axios from "axios"

export default function ajax(url, data = {}, type = "GET") {
  return new Promise((resolve, reject) => {
    let promise
    //发送get请求
    if (type === "GET") {
      //拼接参数
      let dataStr = ""
      Object.keys(data).forEach((key) => {
        dataStr = dataStr + key + "=" + data[key] + "&"
      })
      //去除参数字符串中最后一个&,并拼接url
      if (dataStr !== "") {
        dataStr = dataStr.slice(0, -1)
        url += "?" + dataStr
      }
      //发送请求
      promise = axios.get(url)
    }
    //发送post请求
    else {
      promise = axios.post(url, data)
    }

    //把axios返回的promise对象中的数据(response.data)取出,使用时就减少了一层数据结构
    promise
      .then((response) => {
        resolve(response.data)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
